package com.zone.service.controller;

import java.util.List;
import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zone.common.log.annotation.Log;
import com.zone.common.log.enums.BusinessType;
import com.zone.common.security.annotation.RequiresPermissions;
import com.zone.service.domain.Organization;
import com.zone.service.service.IOrganizationService;
import com.zone.common.core.web.controller.BaseController;
import com.zone.common.core.web.domain.AjaxResult;
import com.zone.common.core.utils.poi.ExcelUtil;
import com.zone.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.zone.common.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import java.net.URLEncoder;
import org.springframework.util.StreamUtils;

/**
 * 机构管理Controller
 * 
 * @author liuyang
 * @date 2025-10-21
 */
@RestController
@RequestMapping("/organization")
public class OrganizationController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(OrganizationController.class);
    
    @Autowired
    private IOrganizationService organizationService;

    /**
     * 查询机构管理列表
     */
    @RequiresPermissions("service:organization:list")
    @GetMapping("/list")
    public TableDataInfo list(Organization organization, @RequestParam(required = false, defaultValue = "true") boolean page)
    {
        if (page) {
            startPage();
        }
        List<Organization> list = organizationService.selectOrganizationList(organization);
        return getDataTable(list);
    }

    /**
     * 导出机构管理列表
     */
    @RequiresPermissions("service:organization:export")
    @Log(title = "机构管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Organization organization)
    {
        List<Organization> list = organizationService.selectOrganizationList(organization);
        ExcelUtil<Organization> util = new ExcelUtil<Organization>(Organization.class);
        util.exportExcel(response, list, "机构管理数据");
    }

    /**
     * 导出机构模板
     */
    @RequiresPermissions("service:organization:export")
    @Log(title = "机构管理", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        String templatePath = "templates/organization.xls";

        ClassPathResource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            logger.error("模板文件不存在: {}", templatePath);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        try {
            // 设置正确的 Content-Type 和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");

            // 安全编码文件名
            String fileName = URLEncoder.encode("机构导入模板.xls", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 流式拷贝（Spring 提供工具类更简洁）
            StreamUtils.copy(resource.getInputStream(), response.getOutputStream());
            response.flushBuffer();

        } catch (IOException e) {
            logger.error("模板下载异常", e);
            try {
                response.reset();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            } catch (IOException ignored) {}
        }
    }

    /**
     * 获取机构管理详细信息
     */
    @RequiresPermissions("service:organization:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(organizationService.selectOrganizationById(id));
    }

    /**
     * 新增机构管理
     */
    @RequiresPermissions("service:organization:add")
    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Organization organization)
    {
        return toAjax(organizationService.insertOrganization(organization));
    }

    /**
     * 修改机构管理
     */
    @RequiresPermissions("service:organization:edit")
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Organization organization)
    {
        return toAjax(organizationService.updateOrganization(organization));
    }

    /**
     * 删除机构管理
     */
    @RequiresPermissions("service:organization:remove")
    @Log(title = "机构管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(organizationService.deleteOrganizationByIds(ids));
    }
    
    /**
     * 导入机构数据
     */
    @RequiresPermissions("service:organization:add")
    @Log(title = "机构管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult execlImport(MultipartFile file, boolean updateSupport) {
        try {
            logger.info("开始导入机构数据");
            
            if (file == null || file.isEmpty()) {
                logger.warn("上传文件为空");
                return AjaxResult.error("上传文件不能为空");
            }
            
            logger.info("文件名: {}, 文件大小: {}", file.getOriginalFilename(), file.getSize());
            
            // 创建ExcelUtil实例
            ExcelUtil<Organization> util = new ExcelUtil<Organization>(Organization.class);
            
            // 解析Excel文件
            List<Organization> organizationList = util.importExcel(file.getInputStream());
            
            // 添加调试信息
            logger.info("解析后的数据条数: {}", organizationList != null ? organizationList.size() : "null");
            
            if (organizationList == null) {
                logger.warn("解析后的数据为null");
                return AjaxResult.error("导入数据解析失败，请检查Excel文件格式");
            }
            
            if (organizationList.isEmpty()) {
                logger.warn("解析后的数据为空列表");
                return AjaxResult.error("导入数据为空，请检查Excel文件是否包含数据");
            }
            
            // 设置创建人
            for (Organization organization : organizationList) {
                organization.setCreateBy(SecurityUtils.getUsername());
            }
            
            return toAjax(organizationService.batchInsertOrganizations(organizationList));
        } catch (Exception e) {
            logger.error("导入机构数据失败: ", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}